from src.service.requests_middler import get_proxies
from src.service.requests_middler import get_abrod_proxies
import requests
import time
from urllib.parse import urlparse

api_key = "CAP-A9F023435886525B40F9D660D233635B"  # your api key of capsolver

def capsolver(websiteURL, captchaUrl):
    proxy = get_abrod_proxies()
    parsed_url = urlparse(proxy['https'])
    user_pass = parsed_url.username + ':' + parsed_url.password
    proxy = proxy['https'].split('@')[-1].split('/')[0] + ":" + user_pass
    # proxy = proxy['https'].split('@')[-1].split('/')[0]
    payload = {
        "clientKey": api_key,
        "task": {
            "type": 'DatadomeSliderTask',
            "websiteURL": websiteURL,
            "captchaUrl": captchaUrl,
            "proxy": proxy,
            "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
        }
    }
    res = requests.post("https://api.capsolver.com/createTask", json=payload)
    resp = res.json()
    task_id = resp.get("taskId")
    if not task_id:
        print("Failed to create task:", res.text)
        return
    print(f"Got taskId: {task_id} / Getting result...")

    while True:
        time.sleep(1)  # delay
        payload = {"clientKey": api_key, "taskId": task_id}
        res = requests.post("https://api.capsolver.com/getTaskResult", json=payload)
        resp = res.json()
        status = resp.get("status")
        if status == "ready":
            return resp.get("solution", {}).get("cookie")
        if status == "failed" or resp.get("errorId"):
            print("Solve failed! response:", res.text)
            return None
